# !/usr/bin/env python
# -*-coding:utf-8 -*-
import os
from influxdb_client import InfluxDBClient, Point, WritePrecision
from datetime import datetime
from influxdb_client.client.write_api import SYNCHRONOUS


class InfluxdbClient:
    def __init__(self, measurement_name="auto_test"):
        url = os.getenv("INFLUXDB_URL", "http://127.0.0.1:8086")
        token = os.environ.get("INFLUXDB_TOKEN", "vj1J1py-ZGTr2xnZ7bWdAvj4Owxbk43CwrR-wK6ywbzZ0kMaT1VEbBue09Xe1-QEehOrLl0eTgd1DippT0kBvQ==")
        org = os.getenv("INFLUXDB_ORG", "FE_Data")
        self.bucket = os.getenv("INFLUXDB_BUCKET", "FE_Data")
        self.measurement_name = measurement_name
        client = InfluxDBClient(url=url, token=token, org=org)
        self.write_api = client.write_api(write_options=SYNCHRONOUS)

    def write_info(self, info_dict: dict):
        points = []
        for key, value in info_dict.items():
            point = Point(self.measurement_name).field(key, value).time(datetime.utcnow(), WritePrecision.NS)
            points.append(point)
        self.write_api.write(bucket=self.bucket, record=points)

